<?php

namespace Admin\Controller;

use Think\Controller;
use Think\Verify;
class LoginController extends Controller{
    public function login(){
        
        
        if(IS_POST){
            $admin_M = D('Admin');
            $data = I('post.');
            unset($data['online']);
            // 验证表单数据
            $res = $admin_M->create($data);
            
            if (!$res){ // 验证不通过
                $this->ajaxReturn(array('status'=>0,'msg'=>$admin_M->getError()));
            }
            
            // 验证用户名是否存在
            $admin_M = M('admin');
            $admin = $admin_M->where(array('name'=>$data['name']))->find();
            
            if(empty($admin)){
                $this->ajaxReturn(array('status'=>0,'msg'=>'用户名不存在'));
            }
            
            // 验证密码是否正确
            if ($admin['password'] != md5(md5($data['password']).LOGIN_PASSWORD)){
                $this->ajaxReturn(array('status'=>0,'msg'=>'密码不正确'));
            }
            
            // 检测验证码
            $verify = new Verify();
            $res = $verify->check($data['code'],'login');
            if(!$res){
                $this->ajaxReturn(array('status'=>0,'msg'=>'验证码错误'));
            }
            
            // 设置用户登陆信息
            $admin['login_time'] = time();
            $admin['login_date'] = date('Ymd');
            $admin['login_count'] = $admin['login_count'] + 1;
            $admin['login_ip'] = $_SERVER['SERVER_ADDR'];
            $admin['login_ip_int'] = ip2long($admin['login_ip']);
            
            $admin_M->save($admin);
            // 记录登陆状态
            session('admin',$admin);
            
            // 是否记住密码
            if (I('post.online') == 1){
                cookie('shop_admin',$data['name'].'|'.$data['password']);
            }else {
                cookie('shop_admin',null);
            }
            
            $this->ajaxReturn(array('status'=>1));
        }else{
            
            // 如果已经登陆了就直接跳转后台首页
            if (session('?admin')){
                $this->redirect('Index/index');die;
            }
            
            //是否记住密码
            if(!empty(cookie('shop_admin'))){
                $admin = explode('|', cookie('shop_admin'));
                $this->assign('admin',$admin);
            }
            // 显示登陆界面
            $this->display();
        }
        
    }
    
    // 获取验证码
    public function getVerify(){
        
        // 创建数组来设置验证码
        $config = array(
            'length' => 4,
            'fontSize' => 15,
        );
        
        // 创建验证码对象
        $verify = new Verify($config);
        
        // 创建验证码
        $verify->entry('login');
    }
    
    // 退出登陆
    function loginOut(){
        // 清除登陆状态
        session('admin',null);
        
        // 跳转登陆界面
        $this->redirect('Login/login');
    }
    
    // 切换账号
    public function changeAdmin(){
        $this->display();
    }
}